﻿using System.Linq.Expressions;

namespace OrderApi.Repositories
{
    public interface IRepository<T> where T : class
    {
        Task<T> GetByIdAsync(int id);
        /// <summary>
        /// 根据ID获取实体（可选禁用查询过滤器）
        /// </summary>
        /// <param name="id">实体ID</param>
        /// <param name="ignoreFilters">是否忽略查询过滤器</param>
        /// <returns>实体对象</returns>
        Task<T?> GetByIdAsync(int id, bool ignoreFilters = false);
        /// <summary>
        /// 分页查询（带条件和可选禁用查询过滤器）
        /// </summary>
        /// <param name="pageNumber">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <param name="filter">过滤条件</param>
        /// <param name="ignoreFilters">是否忽略查询过滤器</param>
        /// <returns>分页结果</returns>
        Task<PagedResult<T>> GetPagedAsync(
            int pageNumber,
            int pageSize,
            Expression<Func<T, bool>>? filter = null,
            bool ignoreFilters = false);
        Task<IEnumerable<T>> GetAllAsync();
        Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate);
        Task AddAsync(T entity);
        void Update(T entity);
        void Remove(T entity);
        Task SaveChangesAsync();
        Task<PagedResult<T>> GetPagedAsync(int pageNumber, int pageSize);
        /// <summary>
        /// 分页查询（带条件）
        /// </summary>
        /// <param name="pageNumber">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <param name="filter">过滤条件</param>
        /// <returns>分页结果</returns>
        Task<PagedResult<T>> GetPagedAsync(
            int pageNumber,
            int pageSize,
            Expression<Func<T, bool>> filter);
        /// <summary>
        /// 根据条件查找单个实体
        /// </summary>
        /// <param name="predicate">查询条件</param>
        /// <returns>匹配的实体或 null</returns>
        Task<T?> FindOneAsync(Expression<Func<T, bool>> predicate);
        /// <summary>
        /// 重新加载实体
        /// </summary>
        /// <param name="entity">要重新加载的实体</param>
        Task ReloadAsync(T entity);
    }
    /// <summary>
    /// 分页查询结果
    /// </summary>
    /// <typeparam name="T">结果数据类型</typeparam>
    public class PagedResult<T>
    {
        /// <summary>
        /// 当前页数据项
        /// </summary>
        public IEnumerable<T> Items { get; set; }
        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotalCount { get; set; }
        /// <summary>
        /// 当前页码
        /// </summary>
        public int PageNumber { get; set; }
        /// <summary>
        /// 每页数量
        /// </summary>
        public int PageSize { get; set; }
        /// <summary>
        /// 总页数（自动计算）
        /// </summary>
        public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize);
    }
}
